#!/bin/bash -eu

local_cookies='/Projects/learnku-deploy-bot/build/cookies.txt'

intro='> :clap: 本系列持续更新中，欢迎关注：**<https://github.com/wi1dcard/laravel-deployment>**。

> 由于课程上下文关联比较紧密，在开始前请先阅读 [本文](https://learnku.com/articles/24914)。

> **你的支持是我写作的动力；关注我的客官们，请在右上角点个赞，将会让文章在首页展示，帮助更多人。**

> 感谢 :clap: ！

<!--more-->
'

leads='轻松部署 Laravel 应用 | '

index=1
deploy() {
    while true
    do
        file=$(echo "$1" | sed -n "${index}p")
        [ ! -z "$file" ] || exit 0
        index=$(($index+1))
        echo

        title="$(echo "$file" | sed -E 's/.+\/(.+)\..+/\1/')"
        echo "Processing: $title"

        id="$(echo "$articles" | grep "$title" | cut -f1)"
        echo "Article ID: $id"

        contents="$(sed -E 's/^# .+$//' "$file")"
        title="${leads}《${title}》"

        temp_file=$(mktemp)
        echo "${intro} ${contents}" > "$temp_file"

        echo "Deploying: $title"
        learnku-deploy-bot article:update \
                -k "$cookies" \
                -t "$token" \
                -i "$id" \
                -l "$title" \
                --tag "轻松部署 Laravel 应用" \
                $temp_file

        rm -f $temp_file
    done
}

persistent_cookies=$([ -z ${LEARNKU_COOKIES+x} ] && cat "$local_cookies" || echo "$LEARNKU_COOKIES" )
cookies=$(learnku-deploy-bot session -k "$persistent_cookies" -r)
echo "Cookies refreshed."

token=$(learnku-deploy-bot token -k "$cookies")
echo "Generated CSRF token: $token"

articles=$(learnku-deploy-bot article:list -k "$cookies")
echo -e "Fetched articles: \n$articles"

files=$(find $(realpath $(dirname $0)/../src/) -name "*.md" | sort)

deploy "$files"
